<?php

namespace app\api\controller;
use app\api\service\Media as MediaService;
use app\api\model\Media as MediaModel;
use think\helper\Str;

class Media extends Base {

  public function __construct() {
    $this->model = new MediaModel();
  }

  public function upload() {

    $file = request()->file('file');
    $ext = $file->getOriginalExtension();
    $service = new MediaService();
    $file = file_get_contents($file);
    $name = date('Ymd', time()) . '/'. strtolower(Str::random(10)) . '.'.$ext;
    $res = $service->uploadOss($name, $file);

    $this->model->save([
      'path' => $res
    ]);
  
    $data = [
      'file'=> $res
    ];
    return success($data);
  }

  public function delete() {
    $id = input('post.id');
    $result = $this->model->where('id', $id)->field('path')->find();

    $arr = explode('/', $result->path);
    $param1 = array_pop($arr);
    $param2 = array_pop($arr);

    $object = 'cms/' . $param2 . '/' . $param1;


    $media = new MediaService();
    $result = $media->deleteOss($object);
    
    $this->model->deleteById($id);
    return success();
  }
  

}

